package com.caac.core.web.resmgr.bean;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

//import com.caac.longcon.cms.common.SystemContext;
import com.caac.core.config.Config;
import com.caac.core.web.resmgr.form.SearchForm;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright 2004</p>
 * <p>Company: </p>
 * @author <a href="mailto:lianzs@caac.com.cn">lianzs</a>
 * @version 1.0
 */
public class ResourceFileHome {

    public static final String DEFAULT_VIRTUAL_ROOT = "/resource";
    private static String root;
    private static String virtualRoot;

    private ResourceFileHome() {
    }

    public static String getRoot() {
        return ResourceFileHome.root;
    }

    public static void setRoot(String root) throws IOException {
        File file = new File(root);
        ResourceFileHome.root = file.getCanonicalPath();
    }

    public static List getDirectoryResFile(String dirName) throws
            UnsupportedEncodingException {

        List files = new ArrayList();
        File path = new File(dirName);
        File[] list = path.listFiles();
        if (list == null) {
            return files;
        }

        for (int i = 0; i < list.length; i++) {
            if (list[i].isFile()) {
                ResFile resFile = makeResFileFromFile(list[i]);
                files.add(resFile);
            }
        }

        return files;
    }

    /*
     * ResFile use UTF-8 encoding for URL encoding, this
     * doesn't work in the Tomcat-LE-Version and I don't
     * know why.
     */
    public static ResFile makeResFileFromFile(File file) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        URLEncoder encoder = new URLEncoder();
        encoder.addSafeCharacter('/');
        encoder.addSafeCharacter('.');

        ResFile resFile = new ResFile();
        resFile.setName(file.getAbsolutePath());
        resFile.setShortName(Directory.getShortName(resFile.getName()));
        resFile.setSize(file.length());
        resFile.setDate(df.format(new Date(file.lastModified())));
        String virtualPath = getVirtualRoot() +
                             resFile.getName().substring(getRoot().length());
        virtualPath = virtualPath.replace('\\', '/');
        //resFile.setVirtualPath(encoder.encode(virtualPath));
        resFile.setVirtualPath(virtualPath);
        return resFile;
    }

    public static List findFile(SearchForm form) {
        List result = new ArrayList();

        File dir = new File(ResourceFileHome.getRoot());
        List subDirectories = new ArrayList();

        // Go through this directory file and directories
        File[] list = dir.listFiles();
        if (list == null) {
            return result;
        }

        for (int i = 0; i < list.length; i++) {
            if (list[i].isFile()) {
                if (ResourceFileHome.isFileMatch(list[i], form)) {
                    ResFile resFile = makeResFileFromFile(list[i]);
                    result.add(resFile);
                }
            } else {
                subDirectories.add(list[i].getAbsolutePath());
            }
        }

        // Iterate through the subdirectories
        Iterator it = subDirectories.iterator();
        while (it.hasNext()) {
            ResourceFileHome.findFile(form, result, (String) it.next());
        }

        return result;
    }

    public static void findFile(SearchForm form, List result, String dirName) {
        File dir = new File(dirName);
        List subDirectories = new ArrayList();

        // Go through this directory file and directories
        File[] list = dir.listFiles();
        if (list == null) {
            return;
        }

        for (int i = 0; i < list.length; i++) {
            if (list[i].isFile()) {
                if (ResourceFileHome.isFileMatch(list[i], form)) {
                    ResFile resFile = makeResFileFromFile(list[i]);
                    result.add(resFile);
                }
            } else {
                subDirectories.add(list[i].getAbsolutePath());
            }
        }

        // Iterate through the subdirectories
        Iterator it = subDirectories.iterator();
        while (it.hasNext()) {
            ResourceFileHome.findFile(form, result, (String) it.next());
        }
        return;
    }

    public static boolean isFileMatch(File file, SearchForm form) {
        if (form.isHasNameCondition() == true) {
            String filename = file.getName().toLowerCase();
            String keyword = form.getNameKeyword().toLowerCase();
            if (filename.indexOf(keyword) == -1) {
                return false;
            }
        }

        if (form.isHasDateCondition() == true) {
            long endMills;
            long startMills;

            if (form.getDateConditionOption().equals("beforeday")) {
                Calendar startDate = Calendar.getInstance();
                startDate.add(Calendar.DAY_OF_MONTH, ( -1) * form.getDayBefore());
                startMills = startDate.getTimeInMillis();
                endMills = System.currentTimeMillis();
            } else if (form.getDateConditionOption().equals("beforemonth")) {
                Calendar startDate = Calendar.getInstance();
                startDate.add(Calendar.MONTH, ( -1) * form.getMonthBefore());
                startMills = startDate.getTimeInMillis();
                endMills = System.currentTimeMillis();
            } else if (form.getDateConditionOption().equals("between")) {
                Calendar startDate = Calendar.getInstance();
                startDate.set(
                        form.getStartYear(),
                        form.getStartMonth() - 1,
                        form.getStartDay());
                Calendar endDate = Calendar.getInstance();
                endDate.set(
                        form.getEndYear(),
                        form.getEndMonth() - 1,
                        form.getEndDay());
                startMills = startDate.getTimeInMillis();
                endMills = endDate.getTimeInMillis();
            } else {
                return false;
            }

            if (file.lastModified() < startMills
                || file.lastModified() > endMills) {
                return false;
            }
        }
        return true;
    }

    public static Directory getDirectoryTree() throws Exception {
        String name = ResourceFileHome.root;
        System.out.println("root:" + name + "   ends;");
        String temproot = null;
        if (ResourceFileHome.root == null) {
            name = DEFAULT_VIRTUAL_ROOT;
            setVirtualRoot(name);

            temproot = Config.getInstance().getRealPath() +
                       DEFAULT_VIRTUAL_ROOT;
            setRoot(temproot);
            return getDirectoryTree(temproot);
        }
        return getDirectoryTree(ResourceFileHome.root);
    }

    public static Directory getDirectoryTree(String name) {
        Directory dir = new Directory();
        dir.setName(name);

        File path = new File(name);
        File[] list = path.listFiles();

        // Get all directories of the filename list.
        List subDirNames = new ArrayList();
        for (int i = 0; i < list.length; i++) {
            if (list[i].isDirectory()) {
                subDirNames.add(list[i].getAbsolutePath());
            }
        }
        dir.setSubDirectories(new Directory[subDirNames.size()]);

        // Iterate though the sub directories
        int i = 0;
        Iterator it = subDirNames.iterator();
        while (it.hasNext()) {
            dir.subDirectories[i] = getDirectoryTree((String) it.next());
            i++;
        }

        return dir;
    }

    public static String getVirtualRoot() {
        return ResourceFileHome.virtualRoot;
    }

    public static void setVirtualRoot(String vr) {
        ResourceFileHome.virtualRoot = vr;
    }
}
